<template>
  <div class="container">
    <div class="app-container">
      <el-tree :data="treeData" :props="{ label: 'name' }" default-expand-all :expand-on-click-node="false">
        <!-- 作用域插槽 data代表每行的数据 -->
        <template #default="{ data }">
          <el-row :style="{ width: '100%' }" type="flex" justify="space-between">
            <div>{{ data.name }}</div>
            <el-row style="width: 140px;" type="flex" justify="space-between">
              <span>{{ data.managerName }}</span>
              <el-dropdown @command="onOperation($event, data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>

                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>

                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>

          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- v-model:  :value  @input -->
    <!-- :xxx.sync:  :xxx  @update:xxx -->

    <!-- 5.1 父传子 -->
    <!-- 2. 导入子组件 注册 使用 -->
    <AddDep ref="addDep" :visible.sync="visible" :current-id="currentId" @refresh="loadData" />

    <!-- <AddDep :visible="visible" @update:visible="visible = $event" /> -->
  </div>
</template>
<script>
import { delDepartmentAPI, getDepartmentAPI } from '@/api/department'
import { arrayToTree } from '@/utils'
import AddDep from './AddDep.vue'

export default {
  name: 'Department',
  components: {
    AddDep
  },
  data() {
    return {
      treeData: [],
      // 1. 存选中的部门id
      currentId: null,
      showDialog: false,
      visible: false
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    async loadData() {
      const res = await getDepartmentAPI()
      const tree = arrayToTree(res)
      this.treeData = tree
    },
    async onOperation(command, id) {
      if (command === 'add') {
        // 4. 修改visible
        this.visible = true
        this.currentId = id// 2. 保存id
      }

      if (command === 'edit') {
        // 4. 修改visible
        await this.$refs.addDep.getDepDetail(id)
        this.visible = true
      }

      if (command === 'del') {
        try {
          await this.$confirm('是否确认取消', '提示一下')
          await delDepartmentAPI(id)
          this.$message.success('删除成功')
          this.loadData()
        } catch (error) {
          console.log('用户点击了删除  ----->  ')
        }
      }
    }
  }
}
</script>

<style  scoped>

.container {
  margin: 30px;
  padding: 30px 140px;
  background-color: white;
}
</style>
